package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2VO;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redissonClient;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        // 查询出 所有的一级分类
        List<CategoryEntity> categoryEntityList = categoryService.getLevel1Categorys();

        model.addAttribute("categorys", categoryEntityList);
        // 视图解析器拼串
        return "index";
    }

    @GetMapping("index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2VO>> getCatelogJson() {
        Map<String, List<Catelog2VO>> map = categoryService.getCatelogJson();
        return map;
    }

    @GetMapping("hello")
    @ResponseBody
    public String hello() throws InterruptedException {
        // 获取一把锁，只要名字一样，就是同一把锁
        /**
         * redisson解决了：
         * 1、锁的自动续期，不用担心没有执行解锁代码导致的死锁问题
         * 2、加锁的业务执行完成，就不会给当前锁续期了
         */
        RLock lock = redissonClient.getLock("my-lock");

        // 加锁
        lock.lock();
        /**
         * lock.lock(10,TimeUnit.SECONDS);
         * 如果指定了超时时间，会直接执行Lua脚本进行加锁，不会自动续期
         * 如果没有指定超时时间，则会使用看门狗执行定时任务 自动续期
         */
        /**
         * 最佳实战
         * lock.lock(30,TimeUnit.SECONDS);
         * lock.unlock();
         */
        try {
            System.out.println("加锁成功：" + Thread.currentThread().getName() + ":" + Thread.currentThread().getId());
            TimeUnit.SECONDS.sleep(30);
        } finally {
            lock.unlock();
            System.out.println("解锁成功：" + Thread.currentThread().getName() + ":" + Thread.currentThread().getId());
        }
        return "hello";
    }

}
